package com.rightsidetech.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.mall.dto.request.*;
import com.rightsidetech.mall.dto.response.*;
import com.rightsidetech.mall.dto.response.CommodityDetailResp;
import com.rightsidetech.mall.dto.response.CommodityDetailSpecsResp;
import com.rightsidetech.mall.dto.response.CommodityOrderDetailResp;
import com.rightsidetech.mall.dto.response.CommodityPageResp;
import com.rightsidetech.mall.entity.*;
import com.rightsidetech.mall.mapper.*;
import com.rightsidetech.mall.service.MallCommodityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.*;
import java.util.stream.Collectors;

@Service("mallCommodityService")
@Slf4j
public class MallCommodityServiceImpl implements MallCommodityService {

    @Resource
    private MallBaseInfoMapper mallBaseInfoMapper;

    @Resource
    private MallCommodityMapper mallCommodityMapper;

    @Resource
    private MallCommodityPictureMapper mallCommodityPictureMapper;

    @Resource
    private MallCommoditySpecsMapper mallCommoditySpecsMapper;

    @Resource
    private MallCommodityAuditRecordMapper mallCommodityAuditRecordMapper;

    @Resource
    private MallAgentCommodityMapper mallAgentCommodityMapper;

    @Resource
    private MallTypeMapper mallTypeMapper;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @Override
    public ResponseData saveCommodity(CommoditySaveReq req, String createrName, Long createrId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallBaseInfoWithBLOBs baseInfo = mallBaseInfoMapper.selectByPrimaryKey(req.getMallBaseId());
        if (ObjectUtil.isEmpty(baseInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"基础商品不存在");
        }
        if(baseInfo.getIsMaintain() == 1){
            return ResponseData.fail("此基础商城已经维护过商城商品不可重新维护");
        }
        List<CommoditySaveSpecsReq> specsList = req.getSpecsList();
        if (CollUtil.isEmpty(specsList)) {
            if (StrUtil.isNotEmpty(baseInfo.getSpecsJson())) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此基础商品有规格,维护商品时不允许没规格");
            }
            return saveCommodityNoSpecs(req, baseInfo, createrName, createrId);
        }
        if (StrUtil.isEmpty(baseInfo.getSpecsJson())) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此基础商品没有规格,维护商品时不允许有规格");
        }
        ResponseData data = checkCommoditySpecs(specsList, req.getIsInNew());
        if (ObjectUtil.isNotEmpty(data)) {
            return data;
        }
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            MallCommodityWithBLOBs record = new MallCommodityWithBLOBs();
            record.setBaseInfoId(baseInfo.getId());
            record.setIsInNew(req.getIsInNew());
            record.setCover(req.getCover());
            record.setPrice(req.getPrice());
            record.setUnderlinedPrice(req.getUnderlinedPrice());
            record.setInNewPrice(req.getInNewPrice());
            record.setCommodityStatus((byte) 0);
            record.setCommodityName(baseInfo.getCommodityName());
            record.setCode(baseInfo.getCode());
            record.setTypeId(baseInfo.getTypeId());
            record.setBrandId(baseInfo.getBrandId());
            record.setSpecsJson(baseInfo.getSpecsJson());
            record.setSpecsDetailJson(JSONUtil.toJsonStr(specsList));
            record.setCreatedAt(new Date());
            record.setCreaterName(createrName);
            record.setCreaterId(createrId);
            if (mallCommodityMapper.insertSelective(record) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("commodityId", record.getId());
            map.put("list", req.getCommodityDetailPicture());
            map.put("pictureType", 1);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            map.put("list", req.getCommodityPicture());
            map.put("pictureType", 0);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            baseInfo = new MallBaseInfoWithBLOBs();
            baseInfo.setId(record.getBaseInfoId());
            baseInfo.setIsMaintain((byte)1);
            if (mallBaseInfoMapper.updateByPrimaryKeySelective(baseInfo) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            if (saveCommoditySpecs(record, specsList, transaction)) {
                return ResponseData.fail("添加失败");
            }
        } catch (Exception e) {
            log.error("添加商品出现异常 {}", e);
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("添加失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    private ResponseData checkCommoditySpecs(List<CommoditySaveSpecsReq> specsList, Byte isInNew) {
        Set<String> codeSet = new HashSet<>();
        for (CommoditySaveSpecsReq specsReq : specsList) {
            ConstraintViolation validate = BeanValidator.validate(specsReq);
            if (validate != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
            }
            //规格名list
            List<DetailSpecsNameReq> nameList = specsReq.getNameList();
            //规格值list
            List<DetailSpecsValueReq> valueList = specsReq.getValueList();
            if(nameList.size() != valueList.size()){
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "规格名与规格值数量不匹配");
            }
            if (isInNew == 0) {
                if (ObjectUtil.isEmpty(specsReq.getInNewPrice())) {
                    return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"支持以旧换新的商品,已旧换新价格不可为空");
                }
            }
            Set<Long> setNameId = new HashSet<>();
            Set<Long> setValueId = new HashSet<>();
            Set<String> setSpecsName = new HashSet<>();
            Set<String> setSpecsValue = new HashSet<>();
            for (int i = 0; i < nameList.size(); i++) {
                DetailSpecsNameReq detailSpecsNameReq = nameList.get(i);
                DetailSpecsValueReq detailSpecsValueReq = valueList.get(i);
                ConstraintViolation validateSpecs = BeanValidator.validate(detailSpecsNameReq);
                if (validateSpecs != null) {
                    return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validateSpecs.getMessage());
                }
                ConstraintViolation validateSpecsValue = BeanValidator.validate(detailSpecsValueReq);
                if(validateSpecsValue != null){
                    return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validateSpecsValue.getMessage());
                }
                setNameId.add(detailSpecsNameReq.getId());
                setValueId.add(detailSpecsValueReq.getId());
                setSpecsName.add(detailSpecsNameReq.getSpecsName());
                setSpecsValue.add(detailSpecsValueReq.getSpecsValue());
            }
            if(setNameId.size() < nameList.size()){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格名称id重复");
            }
            if(setValueId.size() < nameList.size()){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格值id重复");
            }
            if(setSpecsName.size() < nameList.size()){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格名称重复");
            }
            if(setSpecsValue.size() < nameList.size()){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格值重复");
            }
            codeSet.add(specsReq.getCode());
        }
        if(codeSet.size() < specsList.size()){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"规格条码重复");
        }
        return null;
    }

    private ResponseData saveCommodityNoSpecs(CommoditySaveReq req, MallBaseInfoWithBLOBs baseInfo, String createrName, Long createrId) {
        if (req.getIsInNew() == 0) {
            if (ObjectUtil.isEmpty(req.getInNewPrice())) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"允许以旧换新的商品,以旧换新价格不允许");
            }
        }
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            MallCommodityWithBLOBs record = new MallCommodityWithBLOBs();
            record.setBaseInfoId(baseInfo.getId());
            record.setIsInNew(req.getIsInNew());
            record.setPrice(req.getPrice());
            record.setUnderlinedPrice(req.getUnderlinedPrice());
            record.setCommodityStatus((byte) 0);
            record.setCommodityName(baseInfo.getCommodityName());
            record.setCode(baseInfo.getCode());
            record.setCover(req.getCover());
            record.setTypeId(baseInfo.getTypeId());
            record.setBrandId(baseInfo.getBrandId());
            record.setInNewPrice(req.getInNewPrice());
            record.setCreatedAt(new Date());
            record.setCreaterName(createrName);
            record.setCreaterId(createrId);
            if (mallCommodityMapper.insertSelective(record) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("commodityId", record.getId());
            map.put("list", req.getCommodityDetailPicture());
            map.put("pictureType", 1);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            map.put("list", req.getCommodityPicture());
            map.put("pictureType", 0);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            baseInfo = new MallBaseInfoWithBLOBs();
            baseInfo.setId(record.getBaseInfoId());
            baseInfo.setIsMaintain((byte)1);
            if (mallBaseInfoMapper.updateByPrimaryKeySelective(baseInfo) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            MallCommoditySpecs mallCommoditySpecs = new MallCommoditySpecs();
            mallCommoditySpecs.setCommodityId(record.getId());
            mallCommoditySpecs.setPrice(req.getPrice());
            mallCommoditySpecs.setInNewPrice(req.getInNewPrice());
            mallCommoditySpecs.setBarCode("");
            mallCommoditySpecs.setPicture(req.getCover());
            mallCommoditySpecs.setCreatedAt(new Date());
            if (mallCommoditySpecsMapper.insertSelective(mallCommoditySpecs) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
        } catch (Exception e) {
            log.error("添加商品出现异常 {}", e);
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("添加失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<CommodityDetailResp> findDetailById(Long id) {
        if (null == id || id < 0) {
            return ResponseData.fail("id不可为空,或不能为负数");
        }
        CommodityDetailResp result = mallCommodityMapper.selectDetailRespById(id);
        if (ObjectUtil.isEmpty(result)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"没有找到此商品");
        }
        MallType mallType = mallTypeMapper.selectByPrimaryKey(result.getTypeId());
        List<Long> typeIds = new ArrayList<>();
        typeIds.add(result.getTypeId());
        if (mallType != null) {
            String typeName = mallType.getTypeName();
            while (mallType.getParentId() != 0) {
                MallType type = mallTypeMapper.selectByPrimaryKey(mallType.getParentId());
                typeIds.add(type.getId());
                String prentName = type.getTypeName();
                typeName = prentName + "/" + typeName;
                mallType = type;
            }
            result.setTypeName(typeName);
        }
        result.setTypeIds(typeIds);
        List<CommodityDetailSpecsResp> respList = new ArrayList<>();
        if (StrUtil.isNotEmpty(result.getSpecsDetailJson())) {
            List<CommoditySaveSpecsReq> specs = JSONUtil.toList(result.getSpecsDetailJson(), CommoditySaveSpecsReq.class);
            for (CommoditySaveSpecsReq spec : specs) {
                CommodityDetailSpecsResp resp = new CommodityDetailSpecsResp();
                resp.setCode(spec.getCode());
                resp.setPicture(spec.getPicture());
                resp.setInNewPrice(spec.getInNewPrice());
                resp.setPrice(spec.getPrice());
                resp.setValueList(spec.getValueList());
                resp.setNameList(spec.getNameList());
                respList.add(resp);
            }
        }
        result.setSpecsList(respList);
        if(result.getCommodityStatus() == -1){
            result.setAuditContent(mallCommodityAuditRecordMapper.selectAuditContentByCommodityId(result.getId(),"电池商城"));
        }
        result.setCommodityPicture(mallCommodityPictureMapper.selectPictureById(result.getId(), (byte) 0));
        result.setCommodityDetailPicture(mallCommodityPictureMapper.selectPictureById(result.getId(), (byte) 1));
        return ResponseData.success(result);
    }

    @Override
    public ResponseData<PageInfo<CommodityPageResp>> selectPageList(CommodityPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CommodityPageResp> result = mallCommodityMapper.selectCommodityPageList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData updateCommodity(CommodityUpReq req, String updaterName, Long updaterId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallCommodityWithBLOBs commodity = mallCommodityMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(commodity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到要更新的商品");
        }
        MallBaseInfoWithBLOBs baseInfo = mallBaseInfoMapper.selectByPrimaryKey(commodity.getBaseInfoId());
        if (ObjectUtil.isEmpty(baseInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到基础商品");
        }
        if(commodity.getCommodityStatus() == 1){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品待审核不允许修改");
        }
//        if(commodity.getCommodityStatus() == 2){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品待上架中不允许修改");
//        }
        if (commodity.getCommodityStatus() == 3) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此商品已上架不允许修改");
        }
        List<CommoditySaveSpecsReq> specsList = req.getSpecsList();
        if (CollUtil.isEmpty(specsList)) {
            return updateCommodityNoSpecs(req, commodity, updaterName, updaterId);
        }
        ResponseData data = checkCommoditySpecs(specsList, req.getIsInNew());
        if (ObjectUtil.isNotEmpty(data)) {
            return data;
        }
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            if (mallCommoditySpecsMapper.deleteByCommodityId(commodity.getId()) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("更新失败");
            }
            if (saveCommoditySpecs(commodity, specsList, transaction)) {
                return ResponseData.fail("更新失败");
            }
            if (mallCommodityPictureMapper.deleteByCommodityId(commodity.getId()) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("更新失败");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("commodityId", commodity.getId());
            map.put("list", req.getCommodityDetailPicture());
            map.put("pictureType", 1);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("更新失败");
            }
            map.put("list", req.getCommodityPicture());
            map.put("pictureType", 0);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("更新失败");
            }
            MallCommodityWithBLOBs upCommodity = new MallCommodityWithBLOBs();
            upCommodity.setId(commodity.getId());
            upCommodity.setCover(req.getCover());
            upCommodity.setIsInNew(req.getIsInNew());
            upCommodity.setInNewPrice(req.getInNewPrice());
            upCommodity.setPrice(req.getPrice());
            upCommodity.setUnderlinedPrice(req.getUnderlinedPrice());
            upCommodity.setUpdatedAt(new Date());
            upCommodity.setUpdaterName(updaterName);
            upCommodity.setCommodityName(baseInfo.getCommodityName());
            upCommodity.setBrandId(baseInfo.getBrandId());
            upCommodity.setTypeId(baseInfo.getTypeId());
            upCommodity.setCode(baseInfo.getCode());
            upCommodity.setUpdaterId(updaterId);
            upCommodity.setSpecsDetailJson(JSONUtil.toJsonStr(specsList));
            upCommodity.setCommodityStatus((byte) 0);
            if (mallCommodityMapper.updateByPrimaryKeySelective(upCommodity) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("更新失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    private boolean saveCommoditySpecs(MallCommodityWithBLOBs commodity, List<CommoditySaveSpecsReq> specsList,  TransactionStatus transaction) {
        for (int i = 0; i < specsList.size(); i++) {
            CommoditySaveSpecsReq commoditySpecs = specsList.get(i);
            MallCommoditySpecs specs = new MallCommoditySpecs();
            specs.setCommodityId(commodity.getId());
            List<Long> longList = commoditySpecs.getValueList().stream().map(DetailSpecsValueReq::getId).collect(Collectors.toList());
            TreeSet<String> strSet = new TreeSet<>();
            for (Long specsId : longList) {
                strSet.add(specsId + "");
            }
            specs.setSpecsIds(strSet.stream().collect(Collectors.joining(",")));
            specs.setPrice(commoditySpecs.getPrice());
            specs.setInNewPrice(commoditySpecs.getInNewPrice());
            List<DetailSpecsValueReq> valueList = commoditySpecs.getValueList();
            specs.setCommoditySpecs(valueList.stream().map(DetailSpecsValueReq::getSpecsValue).collect(Collectors.joining("、")));
            specs.setBarCode(commoditySpecs.getCode());
            specs.setPicture(commoditySpecs.getPicture());
            specs.setCreatedAt(new Date());
            if (mallCommoditySpecsMapper.insertSelective(specs) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return true;
            }
        }
        return false;
    }

    private ResponseData updateCommodityNoSpecs(CommodityUpReq req, MallCommodityWithBLOBs commodity, String updaterName, Long updaterId) {
        if (StrUtil.isNotEmpty(commodity.getSpecsJson())) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此商品的基础商品有规格,修改时规格不允许为空");
        }
        if (req.getIsInNew() == 0) {
            if (ObjectUtil.isEmpty(req.getInNewPrice())) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"支持以旧换新的商品,以旧换新价格不允许为空");
            }
        }
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            if (mallCommodityPictureMapper.deleteByCommodityId(commodity.getId()) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("修改失败");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("commodityId", commodity.getId());
            map.put("list", req.getCommodityDetailPicture());
            map.put("pictureType", 1);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            map.put("list", req.getCommodityPicture());
            map.put("pictureType", 0);
            if (mallCommodityPictureMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("添加失败");
            }
            mallCommoditySpecsMapper.deleteByCommodityId(commodity.getId());
            MallCommodityWithBLOBs upCommodity = new MallCommodityWithBLOBs();
            upCommodity.setId(commodity.getId());
            upCommodity.setCover(req.getCover());
            upCommodity.setIsInNew(req.getIsInNew());
            upCommodity.setInNewPrice(req.getInNewPrice());
            upCommodity.setPrice(req.getPrice());
            upCommodity.setUnderlinedPrice(req.getUnderlinedPrice());
            upCommodity.setUpdatedAt(new Date());
            upCommodity.setUpdaterName(updaterName);
            upCommodity.setUpdaterId(updaterId);
            upCommodity.setCommodityStatus((byte) 0);
            if (mallCommodityMapper.updateByPrimaryKeySelective(upCommodity) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("修改失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData verifyCommodity(VerifyCommodityReq req, String createrName, Long createrId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallCommodityWithBLOBs commodity = mallCommodityMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(commodity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到需要审核的商品");
        }
        if (commodity.getCommodityStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品状态不正确");
        }
        MallCommodityAuditRecord record = new MallCommodityAuditRecord();
        record.setCommodityId(commodity.getId());
        record.setCreatedName(createrName);
        record.setCreaterId(createrId);
        record.setCreatedAt(new Date());
        record.setCommodityName(commodity.getCommodityName());
        record.setCommodityMarketName("电池商城");
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            if (req.getStatus() == 0) {
                record.setAuditStatus((byte) 1);
                record.setAuditContent(req.getAuditContent());
                if (mallCommodityAuditRecordMapper.insertSelective(record) <= 0) {
                    dataSourceTransactionManager.rollback(transaction);
                    return ResponseData.fail("审核失败");
                }
                MallCommodityWithBLOBs mallCommodity = new MallCommodityWithBLOBs();
                mallCommodity.setId(req.getId());
                mallCommodity.setCommodityStatus((byte) 2);
                if(mallCommodity.getCommoditySort() == null){
                    MallCommodityWithBLOBs sort = mallCommodityMapper.selectBySortDesc();
                    if (sort.getCommoditySort() == null) {
                        mallCommodity.setCommoditySort(1L);
                    } else {
                        mallCommodity.setCommoditySort(sort.getCommoditySort() + 1);
                    }
                }
                if (mallCommodityMapper.updateByPrimaryKeySelective(mallCommodity) <= 0) {
                    dataSourceTransactionManager.rollback(transaction);
                    return ResponseData.fail("审核失败");
                }
                dataSourceTransactionManager.commit(transaction);
                return ResponseData.success(CodeIdEnum.Success);
            }
            if (StrUtil.isBlank(req.getAuditContent())) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"驳回申请必须有驳回理由");
            }
            record.setAuditStatus((byte) -1);
            record.setAuditContent(req.getAuditContent());
            if (mallCommodityAuditRecordMapper.insertSelective(record) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("审核失败");
            }
            commodity = new MallCommodityWithBLOBs();
            commodity.setId(req.getId());
            commodity.setCommodityStatus((byte) -1);
            if (mallCommodityMapper.updateByPrimaryKeySelective(commodity) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("审核失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public CommodityOrderDetailResp findOrderDetailByCommodityId(Long commodityId) {
        return mallCommodityMapper.findOrderDetailByCommodityId(commodityId);
    }

    @Override
    public MallCommodityWithBLOBs selectByPrimaryKey(Long commodityId) {
        return mallCommodityMapper.selectByPrimaryKey(commodityId);
    }

    @Override
    public ResponseData<PageInfo<CommodityAgentResp>> agentPage(AgentPageReq req, Long agentId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("brandId", req.getBrandId());
        map.put("typeId", req.getTypeId());
        map.put("commodityName", req.getCommodityName());
        map.put("agentId", agentId);
        map.put("commodityStatus", req.getCommodityStatus());
        List<CommodityAgentResp> result = mallCommodityMapper.selectAgentPageList(map);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData sort(CommoditySortReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<Long> commodityIds = req.getCommodityId();
        List<Long> sorts = req.getSort();
        if(commodityIds.size() != sorts.size()){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"id与排序数量不一致");
        }
        List<MallCommodity> commoditys = mallCommodityMapper.selectByIds(commodityIds);
        if(CollUtil.isEmpty(commoditys)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到商品");
        }
        if(commodityIds.size() != commoditys.size()){
            return ResponseData.fail("有未找到商品的id");
        }
        for (MallCommodity commodity : commoditys) {
            if (commodity.getCommodityStatus() == -1 || commodity.getCommodityStatus() == 1 || commodity.getCommodityStatus() == 0) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品状态不正确");
            }
        }
        for (int i = 0; i < commodityIds.size(); i++) {
            Long id = commodityIds.get(i);
            Long sort = sorts.get(i);
            if(Long.valueOf(0).equals(sort) || sort < 0){
                sort = null;
            }
            if (mallCommodityMapper.updateSortById(id,sort) <= 0) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"操作失败");
            }
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData agentSort(CommodityAgentSortReq req,Long agentInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<MallAgentCommodity> mallAgentCommodityList = mallAgentCommodityMapper.selectByIds(agentInfoId);
        if(CollUtil.isEmpty(mallAgentCommodityList)){
            return ResponseData.fail("该代理商未绑定商品");
        }
        List<Long> ids = req.getId();
        List<Long> sorts = req.getSort();
        if(ids.size() != sorts.size()){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"id与排序数量不一致");
        }
        if(ids.size() != mallAgentCommodityList.size()){
            return ResponseData.fail("无法排序代理商未绑定的商品");
        }
        List<Long> mallAgentCommodityId = mallAgentCommodityList.stream().filter(Objects::nonNull).map(MallAgentCommodity::getId).collect(Collectors.toList());
        if(ids.retainAll(mallAgentCommodityId)){
            return ResponseData.fail("传入了不存在的id");
        }
//        Set<Long> setSort = new HashSet<>();
//        List<Long> list = req.getSort();
//        list.removeAll(Collections.singleton(Long.valueOf(0)));
//        setSort.addAll(list);
//        if(list.size()>setSort.size()){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"排序id不允许相同");
//        }

//        Map<String,Object> map = new HashMap<>();
//        map.put("agentId",agentInfoId);
//        map.put("list",ids);
//        List<MallAgentCommodity> commoditys = mallAgentCommodityMapper.selectByIds(agentInfoId);
//        if(CollUtil.isEmpty(commoditys)){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到商品");
//        }
//        if(ids.size() != commoditys.size()){
//            return ResponseData.fail("有未找到商品的id,或有商品未上架到此代理商");
//        }
        for (int i = 0; i < ids.size(); i++) {
            Long id = ids.get(i);
            Long sort = sorts.get(i);
            if(Long.valueOf(0).equals(sort) || sort < 0){
                sort = null;
            }
            for (MallAgentCommodity mallAgentCommodity:mallAgentCommodityList) {
                if(id.equals(mallAgentCommodity.getId())) {
                    if (StringUtils.isEmpty(sort) && StringUtils.isEmpty(mallAgentCommodity.getCommodityOrder())) {
                        continue;
                    }
                    if ((StringUtils.isEmpty(sort) && !StringUtils.isEmpty(mallAgentCommodity.getCommodityOrder())) ||
                            (!StringUtils.isEmpty(sort) && !(sort.equals(mallAgentCommodity.getCommodityOrder())))) {
                        if (mallAgentCommodityMapper.updateSortById(id, sort) <= 0) {
                            return ResponseData.fail("排序失败");
                        }
                    }
                }
            }
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData arraignment(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallCommodityWithBLOBs commodity = mallCommodityMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(commodity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到要提审的商品");
        }
        if (commodity.getCommodityStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品状态不正确");
        }
        commodity = new MallCommodityWithBLOBs();
        commodity.setId(req.getId());
        commodity.setCommodityStatus((byte) 1);
        if (mallCommodityMapper.updateByPrimaryKeySelective(commodity) <= 0) {
            return ResponseData.fail("提审失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData popularCommodity(CommodityPopularReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallCommodityWithBLOBs commodity = mallCommodityMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(commodity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到需要设置为爆款的商品");
        }
        if(commodity.getIsPopular().equals(req.getIsPopular())){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此商品已经设置为爆款或已经取消爆款");
        }
        if (commodity.getCommodityStatus() != 2 && commodity.getCommodityStatus() != 3){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"仅待上架和上架中商品可以设置爆款");
        }
        commodity = new MallCommodityWithBLOBs();
        commodity.setId(req.getId());
        commodity.setIsPopular(req.getIsPopular());
        if (mallCommodityMapper.updateByPrimaryKeySelective(commodity) <= 0) {
            return ResponseData.fail("设置失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData isGrounding(CommodityIsGroundingReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallCommodityWithBLOBs mallCommodity = mallCommodityMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(mallCommodity)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到需要操作的商品");
        }
        if(req.getStatus() == 0){
            if(mallCommodity.getCommodityStatus() != 3){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品不是上架状态不允许下架");
            }
            mallCommodity = new MallCommodityWithBLOBs();
            mallCommodity.setId(req.getId());
            mallCommodity.setCommodityStatus((byte)-2);
        }else {
            if(mallCommodity.getCommodityStatus() != 2 && mallCommodity.getCommodityStatus() != -2){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品状态不正确不允许上架");
            }
            mallCommodity = new MallCommodityWithBLOBs();
            mallCommodity.setId(req.getId());
            mallCommodity.setCommodityStatus((byte)3);
        }
        if (mallCommodityMapper.updateByPrimaryKeySelective(mallCommodity) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData deleteAgentByCommodity(Long commodityId){
        if (mallAgentCommodityMapper.deleteByCommodityId(commodityId) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData platformCommodity(MallCommodityWithBLOBs commodity, List<Long> agentIds) {
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            mallAgentCommodityMapper.deleteByCommodityId(commodity.getId());
            Map<String,Object> map = new HashMap<>();
            map.put("commodityId",commodity.getId());
            map.put("list",agentIds);
            if (mallAgentCommodityMapper.insertList(map) <= 0) {
                dataSourceTransactionManager.rollback(transaction);
                return ResponseData.fail("操作失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            dataSourceTransactionManager.rollback(transaction);
            return ResponseData.fail("操作失败");
        }
        dataSourceTransactionManager.commit(transaction);
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData AgentLackStock(AgentLackStockReq req,Long agentInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallAgentCommodity agentCommodity = mallAgentCommodityMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(agentCommodity)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到需要修改的代理商商品");
        }
        if(!agentCommodity.getAgentId().equals(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此商品不属于该代理商");
        }
        agentCommodity = new MallAgentCommodity();
        agentCommodity.setId(req.getId());
        agentCommodity.setCommodityStatus(req.getCommodityStatus());
        if (mallAgentCommodityMapper.updateByPrimaryKeySelective(agentCommodity) <= 0) {
            return ResponseData.fail("修改失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public boolean isUpShelf(Long commodityId) {
        Byte commodityStatus = mallCommodityMapper.selectCommodityStatusById(commodityId);
        if (ObjectUtil.isEmpty(commodityStatus)) {
            return false;
        }
        return commodityStatus == 3;
    }

    @Override
    public MallCommoditySpecs selectSpecsByCommodityAndBarCode(Long commodity, String barCode) {
        return mallCommoditySpecsMapper.selectSpecsByCommodityAndBarCode(commodity,barCode);
    }

    @Override
    public MallCommoditySpecs selectSpecsByCommodityAndSpece(Long commodityId, String spece) {
        return mallCommoditySpecsMapper.selectSpecsByCommodityAndspecs(commodityId, spece);
    }

    @Override
    public boolean isLackStock(Long agentId, Long commodityId) {
        Byte commodityStatus = mallAgentCommodityMapper.selectCommodityStatus(agentId,commodityId);
        if(ObjectUtil.isEmpty(commodityStatus)){
            return false;
        }
        return commodityStatus == 0;
    }

    @Override
    public List<MallAgentCommodity> findAgentCommomdityList(Long commodityId) {
        return mallAgentCommodityMapper.selectByCommodityId(commodityId);
    }

    @Override
    public String selectImg(Long commodityId) {
        return mallCommodityMapper.selectImg(commodityId);
    }

    @Override
    public List<MallAgentCommodityResp> selectById(List<Long> id) {
        List<MallAgentCommodityResp> list = new ArrayList<>();
        id.forEach(i ->{
            list.add(mallAgentCommodityMapper.selectById(i));
        });
        return list;
    }


    @Override
    public ResponseData<List<CommoditySearchResp>> searchCommodity(String commodityName) {
        List<CommoditySearchResp> result =  mallCommodityMapper.selectIdAndName(commodityName);
        return ResponseData.success(result);
    }


    @Override
    public ResponseData<List<CommoditySpescResp>> specsIntegral(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<CommoditySpescResp> result = mallCommoditySpecsMapper.selectSpecsAndCode(req.getId());
        return ResponseData.success(result);
    }

    @Override
    public MallCommoditySpecs selectSpecsByPrimaryKey(Long id) {
        return mallCommoditySpecsMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(MallCommodityWithBLOBs record){
        return mallCommodityMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public ResponseData<List<CommoditySearchResp>> noIntegral(String commodityName) {
        return ResponseData.success(mallCommodityMapper.selectNoIntegral(commodityName));
    }

    @Override
    public boolean checkCommodityByAgentId(Long agentId, Long commodityId) {
        return mallAgentCommodityMapper.selectCountByCommodityIdAndAgentId(commodityId,agentId) > 0;
    }

    @Override
    public ResponseData<List<CommodityInfoResp>> selectMallInfo(Long id,Long agentId) {
        return ResponseData.success(mallCommodityMapper.selectCommInfo(id, agentId));
    }

    @Override
    public CommodityImportResp selectCommodityByCommodityName(String commodityName) {
        return mallCommodityMapper.selectByCommodityName(commodityName);
    }

    @Override
    public ResponseData<List<CommodityPageResp>> selectList(CommodityPageReq req) {
        return ResponseData.success(mallCommodityMapper.selectCommodityPageList(req));
    }

    @Override
    public ResponseData<List<CommodityAgentResp>> agentList(AgentPageReq req,Long agentInfoId) {
        Map<String, Object> map = new HashMap<>();
        map.put("brandId", req.getBrandId());
        map.put("typeId", req.getTypeId());
        map.put("commodityName", req.getCommodityName());
        map.put("agentId", agentInfoId);
        map.put("commodityStatus", req.getCommodityStatus());
        return ResponseData.success(mallCommodityMapper.selectAgentPageList(map));
    }

    @Override
    public ResponseData<List<CommodityPageResp>> selectActivityPageList(CommodityActivityPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<CommodityPageResp> result = mallCommodityMapper.selectCommodityActivityPageList(req);
        return ResponseData.success(result);
    }
}
